package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class ListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
    private ListView mList;
    private ArrayAdapter<String> mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        init();
    }

    private void init() {
        mList=findViewById(R.id.list_view);
        mAdapter=new ArrayAdapter<>(this,R.layout.item_list);
        mList.setAdapter(mAdapter);
        mList.setOnItemClickListener(this);

        loadData();
    }

    private void loadData() {
        String[] data = { "Apple", "Banana", "Orange", "Watermelon",
                "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango",
                "Apple", "Banana", "Orange", "Watermelon", "Pear", "Grape",
                "Pineapple", "Strawberry", "Cherry", "Mango" };
        mAdapter.addAll(data);
        mAdapter.notifyDataSetChanged();//告诉Adapter数据发生变化
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String clicked = mAdapter.getItem(position);

        Toast.makeText(this,clicked,Toast.LENGTH_LONG).show();
    }
}
